const acClient = require("ac-danmu")
const config = require("../../config/config.json")
const fs = require("fs")
const path = require("path")
const _ = require("lodash")
const stepCalc = require("../bussiness/stepCalc")
const memeModel = require("../../models/meme")
const COMMAND_HEARTBEAT = 0
const COMMAND_JOIN_ROOM = 1
const COMMAND_ADD_TEXT = 2
const COMMAND_ADD_GIFT = 3
const COMMAND_ADD_MEMBER = 4
const COMMAND_ADD_SUPER_CHAT = 5
const COMMAND_DEL_SUPER_CHAT = 6
const COMMAND_UPDATE_TRANSLATION = 7
const COMMAND_ADD_LOVE = 8
const COMMAND_QUIT_ROOM = 9
const COMMAND_ADD_FOLLOW = 10
const COMMAND_ADD_JOIN_GROUP = 11
const COMMAND_ADD_ADD_STEP = 12
const COMMAND_ADD_STICKER = 13

const CONFIG_PATH = path.join(process.cwd(), "upload", "config", "users.json")

function processGiftEggs(gift, roomID) {
    let ret = {
        cmd: COMMAND_ADD_GIFT,
        data: {
            roomId: roomID,
            totalValue: gift.value,
            giftName: gift.giftName,
            num: gift.count,
            webpPicUrl: gift.webpPicURL,
            pngPicUrl: gift.pngPicURL,
            ...processUserinfo(gift.user)
        }

    }
    const crafteggId = _.find(config.craftegg, { roomId: Number(roomID) })
    if (crafteggId) {
        const gitfConvert = _.find(crafteggId.eggs.gtif, { origin_name: ret.data.giftName })
        if (gitfConvert) {
            ret.data.giftName = gitfConvert.convert_name;
            ret.data.webpPicUrl = gitfConvert.convert_img_src;
            ret.data.pngPicUrl = gitfConvert.convert_img_src;
        }
    }
    return ret

}

function processDanmukuEggs(danmaku, roomID) {
    let ret = {
        cmd: COMMAND_ADD_TEXT,
        data: {
            content: danmaku.content,
            ...processUserinfo(danmaku.userInfo)
        }
    }
    const gitfConvert = memeModel.MemeFindByCmd(ret.data.content, String(roomID))
    console.log(ret,gitfConvert)
    if (gitfConvert.length >= 1) {
        ret.data['stickerSrc'] = gitfConvert[0].path
    }

    return ret

}


async function MessageHandler(message) {
    const msg = JSON.parse(message)
    this.sendJson = (obj) => {
        try {
            this.send(JSON.stringify(obj))
        } catch (error) {
            console.log(error)
        }
    }
    this.on("close", () => {
        if (this.acClient) {
            this.acClient.removeAllListeners()
            this.acClient = null;
        }
    })
    switch (msg.cmd) {
        case 0:
            this.sendJson({ cmd: COMMAND_HEARTBEAT, data: {} })
            break;
        case 1:
            let userlogin = false;
            let users = ""
            try {
                const json = JSON.parse(fs.readFileSync(CONFIG_PATH).toString("utf-8"))
                if (json.accounts) {
                    users = json.accounts
                    userlogin = true
                } else {
                    userlogin = false
                }
            } catch (error) {
                users = null
            }
            if (!this.acClient) {
                try {
                    this.roomId = msg.data.roomId;
                    this.acClient = await acClient(msg.data.roomId, { login: userlogin, userinfo: users });
                    if (!this.acClient) {
                        this.close();
                    }
                    this.acClient.wsStart();
                } catch (error) {
                    console.log("no live info error,da gai xia bo le")
                    return
                }

            }

            this.acClient.on("decode-error", () => {
                this.close();
            })


            this.acClient.on("enter", () => {
                this.send(`{"cmd":2,"data":{"id":0,"avatarUrl":"https://tx-free-imgs.acfun.cn/style/image/defaultAvatar.jpg","timestamp":1601641021,"authorName":"二号","authorType":0,"privilegeType":0,"translation":"","content":"使用${userlogin ? "登录模式" : "游客模式"}进入${msg.data.roomId}","userMark":"","medalInfo":{"UperID":0,"ClubName":"","Level":0}}}`)
                console.log("entered")
            })

            this.acClient.on("danmaku", (danmaku) => {
                const sc = this.superChatGenerator.genSuperChart(danmaku);
                if (sc) {
                    setTimeout(() => {
                        this.sendJson({
                            cmd: COMMAND_DEL_SUPER_CHAT,
                            data: {
                                ids: [processUserinfo(danmaku.userInfo).id]
                            }
                        })
                    }, sc.duration)
                    this.sendJson({
                        cmd: COMMAND_ADD_SUPER_CHAT,
                        data: {
                            ...sc,
                            ...processUserinfo(danmaku.userInfo)
                        }
                    })

                } else {
                    const retMsg = processDanmukuEggs(danmaku, this.roomId)
                    this.sendJson(retMsg)
                }

            });
            this.acClient.on("gift", (gift) => {
                this.superChatGenerator.genSCinterVal(gift)
                this.sendJson({
                    cmd: COMMAND_ADD_ADD_STEP,
                    data: {
                        step: stepCalc(gift, this.roomId)
                    }
                })
                this.sendJson(processGiftEggs(gift, this.roomId))
            })

            this.acClient.on("user-enter", (info) => {
                const retMsg = {
                    cmd: COMMAND_JOIN_ROOM,
                    data: processUserinfo(info.userInfo)
                }
                this.sendJson(retMsg)
            })

            this.acClient.on("like", (like) => {
                const retMsg = {
                    cmd: COMMAND_ADD_LOVE,
                    data: processUserinfo(like.userInfo)
                }
                this.sendJson(retMsg)
            })

            this.acClient.on("follow", (follow) => {
                const retMsg = {
                    cmd: COMMAND_ADD_FOLLOW,
                    data: processUserinfo(follow.userInfo)
                }
                this.sendJson(retMsg)
            })
            this.acClient.on("join-club", (join) => {
                const retMsg = {
                    cmd: COMMAND_ADD_JOIN_GROUP,
                    data: { id: join.fansInfo.userId, authorName: join.fansInfo.name }
                }
                this.sendJson(retMsg)
            })
        default:
            return;
    }

}

function processUserinfo(userinfo) {

    if (!userinfo) { return {} }

    if (userinfo.badge) {
        let medal = JSON.parse(userinfo.badge).medalInfo
        let medalInfo = {
            ClubName: medal.clubName,
            Level: medal.level,
            UperID: medal.uperId,
            UserID: medal.userId
        }
        return {
            id: userinfo.userId.toNumber(),
            avatarUrl: userinfo.avatar || userinfo.avatar[0] ? userinfo.avatar[0]["url"] : "",
            authorName: userinfo.nickname,
            authorType: 0,
            arivilegeType: 0,
            userMark: "",
            medalInfo: medalInfo
        }
    } else {
        return {
            id: userinfo.userId.toNumber(),
            avatarUrl: userinfo.avatar[0] ? userinfo.avatar[0]["url"] : "",
            authorName: userinfo.nickname,
            authorType: 0,
            arivilegeType: 0,
            userMark: "",
        }
    }

}

module.exports = MessageHandler